<?php
namespace app\admin\controller;

use think\facade\Config;
use think\facade\Db;
use think\facade\View;

class Admin extends Base
{
    public function index(){
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            $map['suppliers_id'] = 0;
            if (session('admin_id') != 1) {
                $map['a.admin_id'] = ['gt', 1];
            }
            if(input('username')){
                $map['a.username'] = input('username');
            }

            if(input('time_start') && input('time_end')){
                $time_start = strtotime(input('time_start'));
                $time_end = strtotime(input('time_end'));
                $map['a.add_time'] = ['between',[$time_start,$time_end]];
            }
            $count = Db::name('admin')->alias('a')->where($map)->count();

            $field = 'a.*';
            $list = Db::name('admin')
                ->alias('a')
                ->where($map)
                ->field($field)
                ->order('a.admin_id desc ')
                ->page($page,$limit)
                ->select();
            $role = Db::name('admin_role')->column('role_name','role_id');
            foreach($list as $k=>$v){
                $v['role'] = $role[$v['role_id']];
                $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                $v['last_login'] = date('Y-m-d H:i:s',$v['last_login']);
                $list[$k] = $v;
            }

            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }

        return View::fetch();
    }

    public function admin_info()
    {
        $admin_id = input('admin_id/d', 0);
        if(!$admin_id){
            $admin_id = session('admin_id');//I('admin_id/d', 0);
        }
        if ($admin_id) {
            $info = Db::name('admin')->where("admin_id", $admin_id)->find();
            $info['password'] = "";
            View::assign('info', $info);
        }
        $act = empty($admin_id) ? 'add' : 'edit';
        View::assign('act', $act);
        $all_role = Db::name('admin_role')->where('is_supply=0')->select();
        View::assign('all_role', $all_role);

        //选出供货商
        View::assign('supplier',Db::name('suppliers')->field('id,name,nickname,mobile')->select()->toArray());
        return View::fetch();
    }
    public function save()
    {
        $data = input('post.');
        if (empty($data['password'])) {
            unset($data['password']);
        } else {
            $data['password'] = encrypt($data['password']);
        }

        if (empty($data['pwd2'])) {
            unset($data['pwd2']);
        } else {
            $data['pwd2'] = encrypt($data['pwd2']);
        }
        if (empty($data['admin_id'])) {
            unset($data['admin_id']);
            $data['add_time'] = time();
            if (Db::name('admin')->where("user_name", $data['user_name'])->count()) {
                return json(['status'=>0,'msg'=>"此用户名已被注册，请更换"]);
            } else {
                $r = Db::name('admin')->insert($data);
            }
        }else{
            if (Db::name('admin')->where("user_name", $data['user_name'])->where(['admin_id'=>['neq',$data['admin_id']]])->count()) {
                return json(['status'=>0,'msg'=>"此用户名已被注册，请更换"]);
            }
            $r = Db::name('admin')->where('admin_id', $data['admin_id'])->update($data);
        }
        return json(['status'=>1,'msg'=>"修改成功"]);

    }
    public function del(){
        $type = input('post.type');
        $ids = input('post.ids','');
        $admin_ids = rtrim($ids,",");
        Db::name('admin')->where('admin_id', 'IN', $admin_ids)->delete();
        return json(['status'=>1,'msg'=>'操作成功']);
    }
    public function loginInfo()
    {
        //$admin_id = input('admin_id/d', 0);
        $admin_id = session('admin_id');
        if ($admin_id) {
            $info = Db::name('admin')->where("admin_id", $admin_id)->find();
            $userInfo = [
                'avatar' => '',
                'nickname' => $info['user_name']
            ];
        }else{
            $userInfo = '';

            $info = Db::name('admin')->where("admin_id", 1)->find();
            session('admin_id',$info['id']);
            $userInfo = [
                'avatar' => '',
                'nickname' => $info['user_name']
            ];
        }
        return json(['code'=>0,'msg'=>'获取成功','data'=> [
            'user'       => $userInfo,
            'authList'   => '',
            'pluginConf' => Config::get('plugin'),
            'ltVersion'  => 1,
        ]]);
    }

    /**
     * 管理员登陆
     */
    public function login()
    {
        if (IS_POST) {
            $username = input('post.username/s');
            $password = input('post.password/s');

            $captcha = trim(input('verify_code'));
            if($captcha == ''){
                return json(['status'=>0,'msg'=>'验证码不能为空']);
            }elseif(!captcha_check($captcha)){
                return json(['status'=>0,'msg'=>'验证码错误']);
            }

            $return = logic('AdminLogic')->login($username, $password);
            if(!$return['status']){
                return json($return);
            }
            $remember = input('remember');
            if($remember){
                cookie('admin_remember',1,3600*24*30);
                cookie('admin_username',$username,3600*24*30);
                cookie('admin_password',encrypt($password),3600*24*30);
            }
            return json(['status'=>1,'msg'=>'登录成功']);
        }

        if (session('?admin_id') && session('admin_id') > 0) {
           header('location:'.url('Index/index'));
        }
        if(cookie('admin_remember')==1){
            $username = cookie('admin_remember');
            $password = cookie('admin_password');
            $return = logic('AdminLogic')->login($username, $password);
            if($return['status']){
                header('location:'.url('Index/index'));
            }
        }

        //$login_bg = tpCache('basic.login_bg');
        $login_bg = '';
        View::assign('login_bg',$login_bg);
        $shop_logo = tpCache('basic.store_logo');
//        $shop_logo = '';
        View::assign('shop_logo',$shop_logo);
        $shop_name = tpCache('basic.store_name');
//        $shop_name = '';
        View::assign('shop_name',$shop_name);
        return View::fetch();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        session(null);
        cookie('admin_remember',null);
        cookie('admin_username',null);
        cookie('admin_password',null);
        return json(['status'=>1,'msg'=>'退出成功！']);
    }

    public function role()
    {
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            $map['a.is_supply'] = 0;

            if(input('username')){
                $map['a.username'] = input('username');
            }

            if(input('time_start') && input('time_end')){
                $time_start = strtotime(input('time_start'));
                $time_end = strtotime(input('time_end'));
                $map['a.add_time'] = ['between',[$time_start,$time_end]];
            }
            $count = Db::name('admin_role')->alias('a')->where($map)->count();

            $field = 'a.*';
            $list = Db::name('admin_role')
                ->alias('a')
                ->where($map)
                ->field($field)
                ->order('a.role_id desc ')
                ->page($page,$limit)
                ->select();
            foreach($list as $k=>$v){

            }

            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        $supply_role = Db::name('admin_role')->where('is_supply',1)->find();
        if(empty($supply_role)){
            Db::name('admin_role')->insert(['role_name'=>'供货商','act_list'=>'all','is_supply'=>1]);
        }
        return View::fetch();
    }

    public function role_info()
    {
        logic('ModuleLogic')->getModules();
        $role_id = input('role_id/d');
        $detail = array();
        if ($role_id) {
            $detail = Db::name('admin_role')->where("role_id", $role_id)->find();
            $detail['act_list'] = explode(',', $detail['act_list']);
            View::assign('detail', $detail);
        }
        $right = Db::name('system_menu')->where('parent','')->order('id')->select();
        foreach ($right as $val) {
            if (!empty($detail)) {
                $val['enable'] = in_array($val['id'], $detail['act_list']);
            }
            $child = Db::name('system_menu')->where('parent',$val['name'])->order('id')->select();
            foreach($child as $ck=>$cv){
                $cv['enable'] = isset($detail['act_list'])?in_array($cv['id'], $detail['act_list']):0;
                $child[$ck] = $cv;
            }
            $val['child'] = $child;
            $modules[$val['group']][] = $val;
        }
        //admin权限组
        $group = logic('ModuleLogic')->getGroup();
        View::assign('group', $group);
        View::assign('modules', $modules);
        return View::fetch('role_info_new');
    }

    public function roleSave()
    {
        $data = input('');
        $res = [];
        $res['role_name'] = $data['role_name']??'';
        $res['role_desc'] = $data['role_desc']??'';
        $res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';
        $res['role_type'] = $data['role_type']??'';
        if($res['role_type']==0){
            $res['act_list'] = 'all';
        }
        if (empty($res['act_list']))
            return json(['status'=>0,'msg'=>"请选择权限!"]);
        if (empty($data['role_id'])) {
            $admin_role = Db::name('admin_role')->where(['role_name' => $res['role_name']])->find();
            if ($admin_role) {
                return json(['status'=>0,'msg'=>"已存在相同的角色名称!"]);
            } else {
                $r = Db::name('admin_role')->insert($res);
            }
        } else {
            $where = [];
            $where[] = ['role_name' ,'=', $data['role_name']];
            $where[] = ['role_id' ,'<>', $data['role_id']];
            $admin_role = Db::name('admin_role')->where($where)->find();
            if ($admin_role) {
                return json(['status'=>0,'msg'=>"已存在相同的角色名称!"]);
            } else {
                $r = Db::name('admin_role')->where('role_id', $data['role_id'])->update($res);
            }
        }
        if ($r!==false) {
            return json(['status'=>1,'msg'=>'操作成功！']);
        } else {
            return json(['status'=>1,'msg'=>'操作失败！']);
        }
    }

    public function roleDel()
    {
        $role_id = input('post.role_id/d');
        $admin = Db::name('admin')->where('role_id', $role_id)->find();
        if ($admin) {
            exit(json_encode("请先清空所属该角色的管理员"));
        } else {
            if($role_id==10){
                return json(['status'=>0,'msg'=>"供货商角色禁止删除!"]);
            }
            $d = Db::name('admin_role')->where("role_id", $role_id)->delete();
            if ($d) {
                exit(json_encode(1));
            } else {
                exit(json_encode("删除失败"));
            }
        }
    }

    public function getLoginNeedCaptchaConf()
    {
        return json(['status'=>1,'data'=>1]);
    }

    public function getConfig(){
        $phpArray = [
            "logo" => [
                "title" => tpCache('basic.store_name'),//网站名称
                "image" => tpCache('basic.store_logo')//网站图标
            ],
            "menu" => [
                "data" => "/admin/Menu/getMenuTree",//菜单数据来源
                "method" => "GET",//菜单接口的请求方式 GET / POST
                "accordion" => true,//是否同时只打开一个菜单目录
                "collapse" => false,//侧边默认折叠状态
                "control" => true,//是否开启多系统菜单模式
                "maxTopMenuNum" => 5,//当 control 为 true 时，顶部最多显示多少菜单，其他顶部菜单需要点击最后的顶部下拉菜单进行展示
                "select" => "2",//默认选中的菜单项
                "async" => true//是否开启异步菜单，false 时 data 属性设置为菜单数据，true 时为 json 文件或后端接口
            ],
            "tab" => [
                "enable" => true,//是否开启多选项卡
                "muiltTab" => true,//是否开启多选项卡
                "keepState" => false,//保持视图状态
                "session" => true,//开启选项卡记忆
                "max" => "30",//最大可打开的选项卡数量
                "index" => [
                    "id" => "2",
                    "href" => "/admin/console.html",//首页 页面地址
                    "title" => "控制面板"
                ]
            ],
            "theme" => [
                "defaultColor" => "2",//默认主题色，对应 colors 配置中的 ID 标识
                "defaultMenu" => "dark-theme",//默认的菜单主题 dark-theme 黑 / light-theme 白
                "defaultHeader" => "light-theme",//默认的顶部主题 dark-theme 黑 / light-theme 白
                "allowCustom" => true,//是否允许用户切换主题，false 时关闭自定义主题面板
                "banner" => false//通栏配置
            ],
            "colors" => [
                [
                    "id" => "1",
                    "color" => "#2d8cf0",
                    "second" => "#ecf5ff",
                    "tableChecked" => "#dbe6fb"
                ],
                [
                    "id" => "2",
                    "color" => "#36b368",
                    "second" => "#f0f9eb",
                    "tableChecked" => "#dbfbf0"
                ],
                [
                    "id" => "3",
                    "color" => "#f6ad55",
                    "second" => "#fdf6ec",
                    "tableChecked" => "#fbf0db"
                ],
                [
                    "id" => "4",
                    "color" => "#f56c6c",
                    "second" => "#fef0f0",
                    "tableChecked" => "#fbe7db"
                ],
                [
                    "id" => "5",
                    "color" => "#3963bc",
                    "second" => "#ecf5ff",
                    "tableChecked" => "#dbe0fb"
                ]
            ],
            "links" => [
                [
                    "icon" => "layui-icon layui-icon-website",
                    "title" => "官方网站",
                    "href" => "http://www.laytp.com"
                ],
                [
                    "icon" => "layui-icon layui-icon-read",
                    "title" => "开发文档",
                    "href" => "https://www.laytp.com/doc.html"
                ],
                [
                    "icon" => "layui-icon layui-icon-fonts-code",
                    "title" => "开源地址",
                    "href" => "https://gitee.com/junstar/laytp"
                ]
            ],
            "other" => [
                "keepLoad" => "500",//主页动画时长
                /**
                 * 布局顶部主题
                 */
                "autoHead" => false,//布局顶部主题
                "footer" => false//页脚
            ],
            "header" => [
                "message" => false//站内消息，数据来源，通过 false 设置关闭
            ]
        ];
        return json($phpArray);
    }
}